package com.moleq.mgpos.activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;

import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.SmartBeep;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.logic.UIManager;
import com.moleq.mgpos.widget.NumberPad;
import com.moleq.mgpos.widget.NumberPadButton;
import com.moleq.mgpos.widget.NumberPad.NumberPadListener;
import com.moleq.models.Functions;
import com.moleq.models.GlobalInfo;
import com.moleq.models.InventorySetting;
import com.moleq.models.PosSetting;
import com.moleq.models.RegKey;
import com.moleq.mgpos.activities.R;
import com.moleq.service.FunctionService;
import com.moleq.service.InventorySettingService;
import com.moleq.service.RegKeyService;
import com.moleq.service.ServiceManager;
import com.moleq.service.UsersService;
import com.moleq.util.MoleQUtil;
import com.moleq.util.SecurityUtil;
import com.moleq.util.StringUtils;

public class LoginActivity extends MoleQBaseActivity {
	private UsersService usersService = null;
	private FunctionService functionService = null;
	private InventorySettingService mInventorySettingService = null;
	private EditText etLoginId, etPwd;
	private GlobalInfo mGlobalInfo;
	private ImageButton imgBtnClose;
	private NumberPad numberPanel;
	private PosSetting possetting;
	private RegKeyService regKeyService = null;
	private static final int APP_CHOOSE = 0;
	private static final int POSRegister = 1;
	private static final int ItemSetting = 2;
	private static final int PriceSetting = 3;
	private static final int DepartmentSetting = 4;
	private static final int POSSetting = 5;
	private static final int UserSetting = 6;
	private static final int HardwareSetting = 7;
	private static final int FlipChartSetting = 8;
	private static final int MixMatchSetting = 9;
	private static final int Reports = 10;
	private static final int EJ = 11;
	private static final int DiscountSetting = 12;
	private static final int MemberSetting = 13;
	private static final int NetWorkSetting = 14;
	private static final int ClerkReport = 15;
	private static final int FunctionSetting = 16;
	private static final int NetworkReport = 17;
	private static final int TerminalReport = 18;
	private static final int ViewSignature = 19;
	private static final int Inventory = 20;
	private int posSettingID;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		this.collapseSoftInputMethod();
		return super.onTouchEvent(event);
	}

	// ==================================================
	// Listener
	// ==================================================
	private OnClickListener OnClickCloseListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			MessageBox.show(LoginActivity.this, getResources().getString(R.string.msg_exit_program), onClickMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
		}

	};

	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			finish();
			System.exit(0);
		}

		@Override
		public void onClickNo() {
			MessageBox.close();
		}

		@Override
		public void onClickOK() {
			// TODO Auto-generated method stub

		}

	};

	private OnTouchListener onTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			EditText ed = new EditText(LoginActivity.this);
			int inType = ed.getInputType();
			ed.setInputType(InputType.TYPE_NULL);
			ed.onTouchEvent(event);
			ed.setInputType(inType);
			ed.setSelection(ed.getText().length());

			switch (v.getId()) {
			case R.id.et_login_num:

				if (etPwd.isFocused()) {
					etPwd.clearFocus();
				}

				UIManager.setFoucesByControl(etLoginId);
				numberPanel.setInputEditText(etLoginId);
				// etLoginId.requestFocus();
				break;
			case R.id.et_password:
				if (etLoginId.isFocused()) {
					etLoginId.clearFocus();
				}
				UIManager.setFoucesByControl(etPwd);
				numberPanel.setInputEditText(etPwd);
				// etPwd.requestFocus();
				break;
			default:
				//
				break;
			}
			return true;
		}
	};

	private NumberPadListener numberPadListener = new NumberPadListener() {

		@Override
		public void onClick(NumberPadButton button) {
			switch (button) {
			case ENTER:

				String usrId,
				usrPwd;

				usrId = etLoginId.getText().toString().trim();
				if (usrId.equals("")) {
					numberPanel.setInputEditText(etLoginId);
					UIManager.setFoucesByControl(etLoginId);
					return;
				}

				usrPwd = etPwd.getText().toString().trim();
				if (usrPwd.equals("")) {
					numberPanel.setInputEditText(etPwd);
					UIManager.setFoucesByControl(etPwd);
					return;
				}
				
				///
//				if (!HaveRegKey()) {
//					MessageBox.show(LoginActivity.this, "Activation Required.");
//					return;
//				}
				
				mGlobalInfo.cashier = usrId;
				InventorySetting mInventorySetting = mInventorySettingService.FindData();
				if(mInventorySetting == null || mInventorySetting.getIs_onoff().equals("0")){
					mGlobalInfo.isInventory = false;
				}else{
					mGlobalInfo.isInventory = true;
				}
				
				
				if (usrId.equals("8888") && usrPwd.equals("8888")) {
					openApp(APP_CHOOSE);
				} else {
					if (usersService.login(usrId, usrPwd)) {
						List<Functions> functions = functionService.getuserfunctionlist(String.valueOf(usersService.FindUserId(usrId)));
						switch (functions.size()) {
						case 0:
							MessageBox.show(LoginActivity.this, getResources().getString(R.string.msg_no_function));
							break;
						case 1:
							openApp(functions.get(0).getFs_id());
							break;
						default:
							openApp(APP_CHOOSE);
							break;
						}
					} else {
						MessageBox.show(LoginActivity.this, getResources().getString(R.string.msg_user_not_exist));
					}
				}

				etLoginId.setText("");
				etPwd.setText("");
				UIManager.setFoucesByControl(etLoginId);
				numberPanel.setInputEditText(etLoginId);
				break;

			default:
				//
				break;
			}

		}

	};
	
	public boolean HaveRegKey(){
		boolean check = true;
		List<RegKey> regkeylist = regKeyService.FindAll();
		if (regkeylist.size() > 0) {
			RegKey mRegKey = regkeylist.get(0);
			String rk_code = mRegKey.getRk_code();
			String rk_key  = mRegKey.getRk_key();
			String local_key = "";
			String macAddress = "";
			if (rk_code != null && !rk_code.equals("")) {
				macAddress = SecurityUtil.getMacAddress(LoginActivity.this);
				local_key = SecurityUtil.encryptToMD5(macAddress+rk_code);
//				local_key = SecurityUtil.encryptToMD5(rk_code);
				
				if (local_key != null && !local_key.equals("")) {
					if (!rk_key.equals(local_key)) {
						
						return false;
					}
				}
			}
		}else{
		
			return false;
		}
		return check;
	}

	public void collapseSoftInputMethod() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// Hidden title
		// Full Screen
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_login);

		// close button
		imgBtnClose = (ImageButton) findViewById(R.id.ibtn_close);
		imgBtnClose.setOnClickListener(OnClickCloseListener);

		// login id and password
		etLoginId = (EditText) findViewById(R.id.et_login_num);
		etLoginId.setOnTouchListener(onTouchListener);

		etPwd = (EditText) findViewById(R.id.et_password);
		etPwd.setOnTouchListener(onTouchListener);

		// number panel
		numberPanel = (NumberPad) this.findViewById(R.id.numberPadLogin);
		numberPanel.setStyle(NumberPad.APPROVAL_STYLE);
		numberPanel.setNumberPadListener(numberPadListener);

		// load sharecontext
		mGlobalInfo = GlobalInfo.getInstance();
		Context sharedContext = GlobalInfo.getInstance().ShareContext;
		Context sharedItyContext = GlobalInfo.getInstance().ShareItyContext;
		ServiceManager.getInstance().buildAllService(sharedContext,sharedItyContext);

		// set currency
		String currency = "";
		possetting = ServiceManager.getInstance().mPosSettingService.Find();
		if (possetting != null) {
			currency = possetting.getCurrency_sign();
			mGlobalInfo.CurrencySign = currency;
			mGlobalInfo.isMGNetwork = possetting.isMGNetwork();
			if (!currency.equals("")) {
				currency = "(" + currency + ")";
			}
			mGlobalInfo.CurrencySymbol = currency;
		}

		SmartBeep.getInstance().dispose();
		SmartBeep.getInstance().reload(this);

		GlobalInfo.getInstance().appDataFolder = this.getApplicationContext().getFilesDir().getAbsolutePath();

		numberPanel.setInputEditText(etLoginId);
		UIManager.setFoucesByControl(etLoginId);
	
		usersService = ServiceManager.getInstance().mUsersService;
		regKeyService = ServiceManager.getInstance().mRegKeyService;
		
		functionService = ServiceManager.getInstance().mFunctionService;
		mInventorySettingService = ServiceManager.getInstance().mInventorySettingService;
	}

	public void openApp(int id) {
		switch (id) {
		case APP_CHOOSE:
			startActivity(new Intent(LoginActivity.this, AppChooseActivity.class));

			break;
		case POSRegister:
			startActivity(new Intent(LoginActivity.this, SaleActivity.class));
			break;
		case ItemSetting:
			startActivity(new Intent(LoginActivity.this, ItemSettingActivity.class));
			break;
		case PriceSetting:
			startActivity(new Intent(LoginActivity.this, PriceSettingActivity.class));
			break;
		case DepartmentSetting:
			startActivity(new Intent(LoginActivity.this, DepartmentSettingActivity.class));
			break;
		case POSSetting:
			startActivity(new Intent(LoginActivity.this, PosSettingActivity.class));
			break;
		case UserSetting:
			startActivity(new Intent(LoginActivity.this, UserSettingActivity.class));
			break;
		case HardwareSetting:
			startActivity(new Intent(LoginActivity.this, HardwareSettingActivity.class));
			break;
		case FlipChartSetting:
			startActivity(new Intent(LoginActivity.this, FlipChartSettingActivity.class));
			break;
		case MixMatchSetting:
			startActivity(new Intent(LoginActivity.this, MixmatchSettingActivity.class));
			break;
		case Reports:
			startActivity(new Intent(LoginActivity.this, ReportActivity.class));
			break;
		case EJ:
			startActivity(new Intent(LoginActivity.this, ElectronicJournalActivity.class));
			break;
		case DiscountSetting:
			startActivity(new Intent(LoginActivity.this, DiscountSettingActivity.class));
			break;
		case MemberSetting:
			startActivity(new Intent(LoginActivity.this, CustomerSettingActivity.class));
			break;
		case NetWorkSetting:
			startActivity(new Intent(LoginActivity.this, NetworkSettingActivity.class));
			break;
		case ClerkReport:
			startActivity(new Intent(LoginActivity.this, ClerkReportActivity.class));
			break;
		case FunctionSetting:
			startActivity(new Intent(LoginActivity.this,
					FunctionSettingActivity.class));
			break;
		case NetworkReport:
			if (ServiceManager.getInstance().mPosSettingService.getRowCount() == 0) {
				MessageBox.show(LoginActivity.this, String.format(getResources().getString(R.string.msg_no_postting), "(POS Setting)"), mNoPosSettingListener, MessageDialog.MESSAGE_BOX_OK);
				return;
			}
			boolean network = ServiceManager.getInstance().mPosSettingService.getAllPosSetting().get(0).isMGNetwork();
			posSettingID = ServiceManager.getInstance().mPosSettingService.getAllPosSetting().get(0).getPs_id();
			if (!network) {
				MessageBox.show(LoginActivity.this, "Do you want to turn ON network feature?", onDialogClickListener, MessageDialog.MESSAGE_BOX_YES_NO);
			}else {
				startActivity(new Intent(LoginActivity.this,
						NetworkReportActivity.class));
			}
			break;
		case TerminalReport:
			startActivity(new Intent(LoginActivity.this,
					TerminalReportActivity.class));
			break;
		case ViewSignature:
			startActivity(new Intent(LoginActivity.this,
					ViewSignatureActivity.class));
			break;
		case Inventory:
			startActivity(new Intent(LoginActivity.this,
					InventoryAppChooseActivity.class));
			break;
			
		default:
			break;
		}
	}
	
	private OnClickMessageListener onDialogClickListener = new OnClickMessageListener() {

		public void onClickYes() {
			ServiceManager.getInstance().mPosSettingService.updatePosNetwork(posSettingID);
			startActivity(new Intent(LoginActivity.this,
					NetworkReportActivity.class));
		}

		public void onClickNo() {
			
		}

		public void onClickOK() {
		}
	};
	
	private OnClickMessageListener mNoPosSettingListener = new OnClickMessageListener() {

		public void onClickYes() {
		}

		public void onClickNo() {
		}

		public void onClickOK() {
			finish();
		}
	};
}
